/*
 * @Author: gonglf
 * @Date: 2022-08-15 09:59:17
 * @LastEditors: gonglf
 * @LastEditTime: 2022-08-19 20:16:32
 * @Description:
 *
 */
package main

import (
	"fmt"
	"net"
	"net/rpc"
	"net/rpc/jsonrpc"
	"sync"
	"time"
)

/*

1、客户端第一次Call会生成一个conn，下次call就复用这个conn
2、客户端多次call好像不会粘包啥的
3、服务端不能主动给客户端发送消息
4、接收器要在rpc上注册
5、客户端请求了一个不存在的方法，能收到请求不会报错也不会执行什么
*/

const (
	URL  = "127.0.0.1:5001"
	URL2 = "127.0.0.1:5002"
)

type Args struct {
	A, B int
}

type Arith int

func (t *Arith) Add(args Args, reply *int) error {
	*reply = args.A + args.B
	fmt.Println("reply", *reply)
	return nil
}

type HelloService struct{}

func (p *HelloService) Hello(request string, reply *string) error {
	*reply = "hello:" + request
	fmt.Println("request", request)
	time.Sleep(5 * time.Second)
	return nil
}

func main() {
	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		tcpAddr, err := net.ResolveTCPAddr("tcp", URL)
		if err != nil {
			fmt.Println(err)
		}
		listener, _ := net.ListenTCP("tcp", tcpAddr)
		for {
			conn, err := listener.Accept()
			if err != nil {
				continue
			}
			go jsonrpc.ServeConn(conn)
		}
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		tcpAddr, err := net.ResolveTCPAddr("tcp", URL2)
		if err != nil {
			fmt.Println(err)
		}
		listener, _ := net.ListenTCP("tcp", tcpAddr)
		for {
			conn, err := listener.Accept()
			if err != nil {
				continue
			}
			go jsonrpc.ServeConn(conn)
		}
	}()

	rpc.Register(new(Arith)) //注册的时机不重要
	rpc.Register(new(HelloService))

	wg.Wait()

}
